/**
 * 易驰护运 - OrderDriverDetail
 * http://menger.me
 * @桓桓
 */

'use strict';

import React from 'react'
import {ImageBackground, Linking, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import {AddressInfo, HorizontalLine, IconFont, ListHeaderLoading, TimeCard, VerticalLine,} from '../../components'
import {Geolocation, MapApp} from 'react-native-baidu-map'
import {inject, observer} from 'mobx-react'
import Webview from 'react-native-webview'
const injectedJavascript = `(function() {
    window.postMessage = function(data) {
      window.ReactNativeWebView.postMessage(data);
    };
  })()`;
@inject('loginStore')
@observer
export default class OrderDriverDetail extends React.Component {
    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            dataSource: [],
            timeDataSource: [],
            loading_img_status: '',
            discharge_img_status: '',
            isRefreshing: false,
            address: '',
            warp: '',
            weft: '',

            from_address: '',
            from_warp: '',
            from_weft: '',
            to_address: '',
            to_warp: '',
            to_weft: '',
        }
    }

    componentDidMount() {
        this.requestData();
        this.requestTimeCardData();
        this.getCurrentPosition();
    }

    _onRefresh = async () => {
        this.setState({isRefreshing: true});
        this.requestData();
        this.getCurrentPosition();
        this.requestTimeCardData();
        setTimeout(() => this.setState({isRefreshing: false}), 500);
    };

    getCurrentPosition = () => {
        Geolocation.getCurrentPosition()
            .then(data => {
                console.log(data)
                this.setState({
                    warp: data.longitude,
                    weft: data.latitude,
                })
            })
            .catch(e => {
                console.warn(e, 'error');
            })
    }

    // 请求页面信息
    requestData = async () => {
        let {item} = this.params;
        let url = ServicesApi.VEHICLE_ORDER_INFO;
        let data = {
            id: item.id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                dataSource: result.data,
                from_address: result.data.from_address,
                from_warp: result.data.from_warp,
                from_weft: result.data.from_weft,
                to_address: result.data.to_address,
                to_warp: result.data.to_warp,
                to_weft: result.data.to_weft,
                loading: false,
            });
        }
    }

    // 请求时间轴数据
    requestTimeCardData = async () => {
        let {item} = this.params;
        let url = ServicesApi.VEHICLE_ORDER_LOG;
        let data = {
            vehicle_order_id: item.id,
        };
        const result = await Services.post(url, data);
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.setState({
                timeDataSource: result.data.dataList,
                loading_img_status: result.data.status.loading_img_status,
                discharge_img_status: result.data.status.discharge_img_status,
            });
        }
    }

    openMap = (type) => {
        let params = {
            title: '即将离开APP',
            detail: '为了给您带来更好的体验，请确保您的手机中安装有百度地图APP。',
            actions: [
                {title: '取消',},
                {title: '确定', onPress: () => this.openBaiduMapApp(type)},
            ],
        };
        AlertManager.show(params);
        return true;
    }

    openBaiduMapApp = (type) => {
        let {address, warp, weft, from_address, from_warp, from_weft, to_address, to_warp, to_weft} = this.state;
        if (type == 'start') {
            MapApp.openDrivingRoute(
                {latitude: Number(weft), longitude: Number(warp), name: address},
                {latitude: Number(from_weft), longitude: Number(from_warp), name: from_address},
            )
        } else if (type == 'end') {
            MapApp.openDrivingRoute(
                {latitude: Number(weft), longitude: Number(warp), name: address},
                {latitude: Number(to_weft), longitude: Number(to_warp), name: to_address},
            )
        }
    }

    onMakeCall = (data) => {
        Linking.openURL('tel:' + data).catch(e => console.log(e));
    }

    render() {
        let pageTitle = this.params.pageTitle || '司机订单详情';
        let {item, type} = this.params;
        let {loading, dataSource, timeDataSource, discharge_img_status} = this.state;
        return (
            <PageContainer loading={loading} style={styles.container}>
                <NavigationBar 
                    title={pageTitle} 
                    style={styles.navigationBar}
                />
                <View style={styles.headerPadding}/>
                <ScrollView
                    style={styles.content}
                    refreshControl={<ListHeaderLoading onRefresh={this._onRefresh} refreshing={this.state.isRefreshing}/>}
                >
                    <View>
                        <View style={[styles.contentItemView, styles.contentSmallItemView]}>
                            <View style={styles.contentItemBgView}/>
                            <ImageBackground
                                resizeMode={'stretch'}
                                style={styles.detailAddressView}
                                source={Images.img_bg_block_content}
                            >
                                <AddressInfo item={dataSource} style={styles.addressInfoStyle}/>
                                <HorizontalLine style={styles.addressInfoSeparator}/>
                                <View style={[Predefine.RCB, styles.cargoInfoCardContent]}>
                                    <View style={[Predefine.CCC, styles.cargoInfoCardItemView]}>
                                        <Text style={styles.cargoInfoCardItemValue}
                                                numberOfLines={2}>{dataSource.goods_name}</Text>
                                        <View style={[Predefine.RCC, styles.cargoInfoCardItemTitleView]}>
                                            <ImageView source={Images.icon_text}
                                                        style={styles.cargoInfoCardItemTitleIcon}/>
                                            <Text style={styles.cargoInfoCardItemTitle}>货物名称</Text>
                                        </View>
                                    </View>
                                    <VerticalLine style={styles.cargoInfoCardSeparator}/>
                                    <View
                                        style={[Predefine.CCC, styles.cargoInfoCardItemView, styles.cargoInfoCardItemViewCenter]}>
                                        <Text style={styles.cargoInfoCardItemValue}
                                                numberOfLines={2}>{dataSource.goods_dangerous_level_text}</Text>
                                        <View style={[Predefine.RCC, styles.cargoInfoCardItemTitleView]}>
                                            <ImageView source={Images.icon_grid}
                                                        style={styles.cargoInfoCardItemTitleIcon}/>
                                            <Text style={styles.cargoInfoCardItemTitle}>货物类型</Text>
                                        </View>
                                    </View>
                                    <VerticalLine style={styles.cargoInfoCardSeparator}/>
                                    <View style={[Predefine.CCC, styles.cargoInfoCardItemView]}>
                                        <Text style={styles.cargoInfoCardItemValue}
                                                numberOfLines={2}>{dataSource.goods_weight}</Text>
                                        <View style={[Predefine.RCC, styles.cargoInfoCardItemTitleView]}>
                                            <ImageView source={Images.icon_rank}
                                                        style={styles.cargoInfoCardItemTitleIcon}/>
                                            <Text style={styles.cargoInfoCardItemTitle}>货物重量</Text>
                                        </View>
                                    </View>
                                </View>
                            </ImageBackground>
                            <Text style={styles.orderId} numberOfLines={1}>订单号：{dataSource.vehicle_order_no}</Text>
                        </View>
                        <View style={styles.card}>
                            <View style={styles.cardHeader}>
                                <View style={styles.cardHeaderBall}><View
                                    style={styles.cardHeaderBallCenter}/></View>
                                <Text style={styles.cardHeaderText} numberOfLines={1}>详细地址</Text>
                            </View>
                            <View style={styles.cardHeaderBox}>
                                <View style={styles.cardHeaderBoxRight}>
                                    <View style={styles.cardLine}>
                                        <Text style={[styles.cardLineLeft, {color: '#00BFCC', fontSize: 15}]} numberOfLines={1}>发货地</Text>
                                    </View>
                                    <IconFont.Feather name={'phone-call'} size={26} color={'#1E90FF'} style={styles.cardHeaderIcon} onPress={() => this.onMakeCall(dataSource.from_mobile)}/>
                                    <IconFont.Foundation name={'map'} size={26} color={'#32CD32'} style={styles.cardHeaderIcon} onPress={() => this.openMap('start')}/>
                                </View>
                                <TouchableOpacity style={styles.cardLineBox}>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>姓名：</Text>
                                        <Text style={styles.cardLineRight}
                                                numberOfLines={1}>{dataSource.from_contact}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>联系方式：</Text>
                                        <Text style={styles.cardLineRight}
                                                numberOfLines={1}>{dataSource.from_mobile}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>地点名称：</Text>
                                        <Text style={[styles.cardLineRight, {color: '#00BFCC'}]}
                                                numberOfLines={1}>{dataSource.from_company}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>详细地址：</Text>
                                        <Text style={styles.cardLineRight}
                                                numberOfLines={1}>{dataSource.from_province + dataSource.from_city + dataSource.from_district + dataSource.from_address}</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                            <View style={styles.cardHeaderBox}>
                                <View style={styles.cardHeaderBoxRight}>
                                    <View style={styles.cardLine}>
                                        <Text style={[styles.cardLineLeft, {color: '#00BFCC', fontSize: 15}]} numberOfLines={1}>目的地</Text>
                                    </View>
                                    <IconFont.Feather name={'phone-call'} size={26} color={'#1E90FF'} style={styles.cardHeaderIcon} onPress={() => this.onMakeCall(dataSource.to_mobile)}/>
                                    <IconFont.Foundation name={'map'} size={26} color={'#32CD32'} style={styles.cardHeaderIcon} onPress={() => this.openMap('end')}/>
                                </View>
                                <TouchableOpacity style={styles.cardLineBox}>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>姓名：</Text>
                                        <Text style={styles.cardLineRight}
                                                numberOfLines={1}>{dataSource.to_contact}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>联系方式：</Text>
                                        <Text style={styles.cardLineRight}
                                                numberOfLines={1}>{dataSource.to_mobile}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>地点名称：</Text>
                                        <Text style={[styles.cardLineRight, {color: '#00BFCC'}]}
                                                numberOfLines={1}>{dataSource.to_company}</Text>
                                    </View>
                                    <View style={styles.cardLine}>
                                        <Text style={styles.cardLineLeft} numberOfLines={1}>详细地址：</Text>
                                        <Text style={styles.cardLineRight} numberOfLines={1}>{dataSource.to_province + dataSource.to_city + dataSource.to_district + dataSource.to_address}</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </View>
                    <TimeCard
                        item={timeDataSource}
                        loading_img_status={discharge_img_status}
                        discharge_img_status={discharge_img_status}
                        {...this.props}
                    />
                    {
                        (dataSource.vehicle_order_status === 6 && type == null) && // 待送达
                        <View style={styles.bottomBtnBox}>
                            <Button
                                style={styles.bottomBtn}
                                title={'查看电子运单'}
                                titleStyle={styles.bottomBtnTitle}
                                resizeMode={'cover'}
                                backgroundImage={Images.img_btn_bg1}
                                onPress={() => RouterHelper.navigate('', 'ElectronicsDriverOrder', {item})}
                            />
                        </View>
                    }
                </ScrollView>
            </PageContainer>
        );
    }
}

const DominantColor = '#00BFCC';
const contentWidth = Predefine.screenWidth - 20;
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    navigationBar: {
        zIndex: 10,
        position: 'absolute',
    },
    headerPadding: {
        height: NAV_BAR_HEIGHT,
    },
    rightAction: {
        width: 20,
        height: 20,
    },
    content: {
        
    },
    navItemStyle: {
        marginTop: 10,
    },

    contentItemView: {
        minHeight: 100,
        marginBottom: 10,
        paddingVertical: 15,
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    contentSmallItemView: {
        paddingHorizontal: 10,
    },
    contentItemBgView: {
        top: 0,
        left: 0,
        height: 100,
        position: 'absolute',
        width: Predefine.screenWidth,
        backgroundColor: Predefine.themeColor,
    },
    detailAddressView: {
        width: contentWidth,
        paddingVertical: 15,
        paddingHorizontal: 15,
        // height: contentWidth * 0.45,
    },
    addressInfoStyle: {
        marginVertical: 0,
    },
    addressInfoSeparator: {
        marginVertical: 5,
        backgroundColor: Predefine.themeColor,
    },
    // 顶部发片底部的信息（货物名称，货物类型，货物重量）
    cargoInfoCardContent: {
        marginTop: 10,
    },
    cargoInfoCardItemView: {
        flex: 2,
    },
    cargoInfoCardItemViewCenter: {
        flex: 3,
    },
    cargoInfoCardItemValue: {
        fontSize: 14,
        fontWeight: '700',
        textAlign: 'center',
        color: Predefine.themeColor,
    },
    cargoInfoCardItemTitleView: {
        marginTop: 5,
    },
    cargoInfoCardItemTitle: {
        fontSize: 12,
        color: '#666',
    },
    cargoInfoCardItemTitleIcon: {
        width: 12,
        height: 12,
        marginRight: 3,
    },
    cargoInfoCardSeparator: {
        width: 1,
        height: 25,
        backgroundColor: Predefine.themeColor,
    },
    orderId: {
        marginTop: 10,
        fontSize: 12,
        color: '#333',
    },

    card: {
        marginBottom: 10,
        backgroundColor: '#fff',
        paddingHorizontal: 15,
    },
    cardHeader: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
    },
    cardHeaderBox: {
        borderTopWidth: Predefine.minPixel,
        borderTopColor: '#F0F0F0',
    },
    cardHeaderIcon: {
        marginLeft: 15,
        marginTop: 10,
    },
    cardHeaderBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    cardHeaderBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#fff',
    },
    cardHeaderText: {
        color: '#333',
        fontSize: 15,
        fontWeight: 'bold',
    },

    cardLineBox: {
        flex: 1,
    },
    cardHeaderBoxRight: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
    },
    cardLine: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 30,
    },
    cardLineLeft: {
        color: '#333',
        fontSize: 14,
    },
    cardLineRight: {
        color: '#666',
        fontSize: 14,
        flex: 1,
        textAlign: 'right',
    },

    addressBox: {
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#fff',
        marginBottom: 10,
        paddingHorizontal: 15,
        paddingVertical: 10,
    },
    addressBoxImg: {
        width: 32,
        height: 32,
        marginRight: 10,
    },
    addressBoxText: {
        fontSize: 15,
        color: '#333',
        flex: 1,
        lineHeight: 20,
    },

    // 底部的按钮
    bottomBtnBox: {
        paddingVertical: 10,
        paddingHorizontal: 15,
        backgroundColor: '#fff',
    },
    bottomBtn: {
        backgroundColor: DominantColor,
        borderRadius: 5,
    },
    bottomBtnTitle: {},

    webContainer: {
        height: SCREEN_WIDTH,
        width: SCREEN_WIDTH,
    },
});